package com.devicemantra.coordinate.interfaces.http;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import com.devicemantra.coordinate.interfaces.sms.SMSFactory;
import com.google.appengine.repackaged.com.google.common.util.Base64;


public class CHttpPost 
{
	public CHttpPost() {}
	
	public void send(String pMessage)
	{
		String message = null;
		try {
            URL url = new URL("http://www.smartcall.ae/esmsnetclientapi/submitXML.aspx");
            //URL url = new URL("http://www.devicemantra.com/smartcall/receive_sms.php");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "text/plain");
            setBasicAuth(connection,SMSFactory.getUserName(),SMSFactory.getPassword());
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(pMessage);
            writer.close();
    
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                System.out.println("200 0K Received");
            } else {
            	System.out.println("Server returned HTTP error code.");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
        	e.printStackTrace();
            // ...
        }
	}
	
	
	 /**
     * Preemptively set the Authorization header to use Basic Auth.
     * @param connection The HTTP connection
     * @param username Username
     * @param password Password
     */
    public void setBasicAuth(HttpURLConnection connection,
                String username, String password)
    {
        StringBuilder buf = new StringBuilder(username);
        buf.append(':');
        buf.append(password);
        byte[] bytes = null;
        try {
                bytes = buf.toString().getBytes("ISO-8859-1");
        } catch (java.io.UnsupportedEncodingException uee) {
                assert false;
        }

        String header = "Basic " + Base64.encode(bytes);
        connection.setRequestProperty("Authorization", header);
    }
}
